import { defineStore } from "pinia";
import {
  getLiveWeather,
  getWeatherForecast,
  getCitycodeByip,
  getCitycodeByName,
} from "../api/request";

// 获取本地城市信息
// 通过ip获取城市信息
// 通过城市adcode获取实况天气信息
// 通过城市adcode获取天气预报信息
export const useLocalStore = defineStore("local", {
  state: () => ({
    localcity: {},
    localweather: {},
    localforecast: [],
  }),
  actions: {
    async getLocalInfo() {
      const res = (await getCitycodeByip()).data;
      this.localcity = res;
      this.localweather = (await getLiveWeather(res.adcode)).data.lives[0];
      this.localforecast = (
        await getWeatherForecast(res.adcode)
      ).data.forecasts[0].casts;
    },
  },
});

// 获取搜索城市的信息
// 1.通过城市名称获取城市adcode
// 2.通过城市adcode获取实况天气信息
// 3.通过城市adcode获取天气预报信息
export const useSearchStore = defineStore("search", {
  persist: {
    enabled: true,
    paths: ["CityList"],
  },
  state: () => ({
    searchcity: {},
    searchweather: {},
    searchforecast: [],
    CityList: [],
  }),
  actions: {
    async getSearchInfo(cityname) {
      const res = (await getCitycodeByName(cityname)).data;
      this.searchcity = res.districts[0];
      this.searchweather = (
        await getLiveWeather(this.searchcity.adcode)
      ).data.lives[0];
      this.searchforecast = (
        await getWeatherForecast(this.searchcity.adcode)
      ).data.forecasts[0].casts;
    },
    AddCityList(e) {
      this.getSearchInfo(e);
      const item = {
        name: this.searchcity.name,
        id: this.searchcity.adcode,
      };
      this.CityList.push(item);
    },
    // 删除城市列表中的数据
    removeCity(e) {
      this.CityList = this.CityList.filter((item) => item.id !== e);
    },
  },
});
